package database.paydetail;

import database.CRUD;
import database.GUImanager;
import database.Redis;
import database.employee.EmployeeCURDGUI;
import database.employee.tb_employee;
import redis.clients.jedis.Jedis;

import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.*;
import java.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;

public class PaydetailCURDGUI {
    private DefaultTableModel model;
    private JTable table;
    JFrame framepaydetail;
    public PaydetailCURDGUI(tb_employee e1) throws SQLException {
        framepaydetail=new JFrame();
        DefaultTableModel model;
        table = new JTable();
        table.setRowSelectionAllowed(true); // 允许通过点击选择行
        ListSelectionModel selectionModel = table.getSelectionModel();
        selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // 或者使用多选 ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
        DefaultTableModel tableModel;
        int selectedRow; // 用于记录选中的行

        // 数据库连接信息
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "123456");
        Statement stmt = conn.createStatement();
        String query = "SELECT * FROM " + "tb_pay_detail";
        ResultSet rs = stmt.executeQuery(query);
        framepaydetail.setTitle("超市管理系统");
        framepaydetail.setBounds(100,100,800,600); // 设置窗口大小
        framepaydetail.setDefaultCloseOperation(DISPOSE_ON_CLOSE); // 设置默认关闭操作
        framepaydetail.setLocationRelativeTo(null); // 居中显示

        // Get metadata from ResultSet
        ResultSetMetaData metaData = rs.getMetaData();
        int columnCount = metaData.getColumnCount();
        String[] columnNames = new String[columnCount];
        for (int i = 0; i < columnCount; i++) {
            columnNames[i] = metaData.getColumnName(i + 1); // Columns in ResultSet start from index 1
        }

        // Create table model with columns from metadata
        model = new DefaultTableModel(columnNames, 0); // 0 rows initially
        table.getModel().addTableModelListener(new TableModelListener() {
            @Override
            public void tableChanged(TableModelEvent e) {
                if (e.getType() == TableModelEvent.UPDATE && e.getColumn() != -1) {
                    int rowIndex = e.getFirstRow();
                    int columnIndex = e.getColumn();
                    Object value = model.getValueAt(rowIndex, columnIndex);
                    // 检查单元格是否是新值，且不是主键列
                    if (rowIndex == table.getSelectedRow()) {
                        updateSelectedRow();
                    }
                }
            }
        });
        // Populate table model with data from ResultSet
        while (rs.next()) {
            Object[] rowData = new Object[columnCount];
            for (int i = 0; i < columnCount; i++) {
                rowData[i] = rs.getObject(i + 1); // ResultSet columns start from index 1
            }
            model.addRow(rowData);
        }

        // Create JTable with the model
        table = new JTable(model);

        // Create a scroll pane for the table
        JScrollPane scrollPane = new JScrollPane(table);
        framepaydetail.add(scrollPane, BorderLayout.CENTER);

        // Panel for buttons
        JPanel buttonPanel = new JPanel();
        JButton addButton = new JButton("新增");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    openAddDialog(e1);
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
        buttonPanel.add(addButton);

        JButton deleteButton = new JButton("删除");
        deleteButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                deleteSelectedRows();
            }
        });
        buttonPanel.add(deleteButton);

        JButton updateButton = new JButton("更新");
        updateButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                  updateSelectedRow();
            }
        });
        buttonPanel.add(updateButton);
        JButton ExportButton = new JButton("导出");
        ExportButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                exportSelectedRowToCsv(table);
            }
        });
        buttonPanel.add(ExportButton);
        JButton returnButton =new JButton("返回");
        returnButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new GUImanager(e1);
                new Redis("tb_pay_detail");
                framepaydetail.dispose();
            }
        });
        buttonPanel.add(returnButton);
        framepaydetail.add(buttonPanel, BorderLayout.SOUTH);

        framepaydetail.setVisible(true);
    }

    private void openAddDialog(tb_employee e1) throws SQLException {
        framepaydetail.dispose();
        JFrame addFrame = new JFrame("新增详细采购信息");
        addFrame.setSize(800, 600);
        addFrame.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
        addFrame.setLocationRelativeTo(null); // 居中显示
        JPanel addPanel = new JPanel(new BorderLayout());
        CRUD crud = new CRUD(); // Assuming CRUD class handles database operations
        Connection conn = crud.getConnection();

        // 查询 tb_pay_main 和 tb_good 表以填充 JComboBox
        String payMainQuery = "SELECT Pid FROM tb_pay_main";
        String goodQuery = "SELECT Gid FROM tb_good";
        List<String> pidList = new ArrayList<>();
        List<String> gidList = new ArrayList<>();
        try (Statement stmt = conn.createStatement()) {
            // 填充 tb_pay_main 的 Pid
            try (ResultSet rs = stmt.executeQuery(payMainQuery)) {
                while (rs.next()) {
                    pidList.add(rs.getString("Pid"));
                }
            }
            // 填充 tb_good 的 Gid
            try (ResultSet rs = stmt.executeQuery(goodQuery)) {
                while (rs.next()) {
                    gidList.add(rs.getString("Gid"));
                }
            }
        } catch (SQLException ex) {
            ex.printStackTrace();
            JOptionPane.showMessageDialog(null, "加载编号失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 获取 tb_pay_detail 表的列名
        String query = "SELECT * FROM tb_pay_detail WHERE 1=0"; // 使用 WHERE 1=0 来避免获取数据，只获取元数据
        try (Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery(query)) {
            ResultSetMetaData metaData = rs.getMetaData();
            int columnCount = metaData.getColumnCount();
            String[] columnNames = new String[columnCount];

            for (int i = 0; i < columnCount; i++) {
                columnNames[i] = metaData.getColumnName(i + 1);
            }

            // 创建表格模型并初始化列名
            DefaultTableModel addTableModel = new DefaultTableModel(columnNames, 0);

            // 创建 JTable
            JTable addTable = new JTable(addTableModel);

            // 为 Pid 和 Gid 列创建 JComboBox 编辑器
            JComboBox<String> pidComboBox = new JComboBox<>(pidList.toArray(new String[0]));
            JComboBox<String> gidComboBox = new JComboBox<>(gidList.toArray(new String[0]));
            int pidColumnIndex = Arrays.asList(columnNames).indexOf("Pid");
            int gidColumnIndex = Arrays.asList(columnNames).indexOf("Gid");
            if (pidColumnIndex != -1) {
                addTable.getColumnModel().getColumn(pidColumnIndex).setCellEditor(new DefaultCellEditor(pidComboBox));
            }
            if (gidColumnIndex != -1) {
                addTable.getColumnModel().getColumn(gidColumnIndex).setCellEditor(new DefaultCellEditor(gidComboBox));
            }

            // 将 JTable 添加到 JScrollPane
            JScrollPane addScrollPane = new JScrollPane(addTable);

        JButton addButton = new JButton("新增");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // Add a blank row to the table
                addTableModel.addRow(new Object[addTableModel.getColumnCount()]);
            }
        });

        JButton saveButton = new JButton("保存");
        saveButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                try {
                    if (addTableModel.getRowCount() == 0) {
                        JOptionPane.showMessageDialog(addFrame, "表格为空，没有数据需要保存。", "提示", JOptionPane.INFORMATION_MESSAGE);
                        return; // 直接返回，不执行保存操作
                    }
                    // 构建并执行插入语句
                    for (int i = 0; i < addTableModel.getRowCount(); i++) {
                        // Prepare an SQL INSERT statement
                        StringBuilder sb = new StringBuilder("INSERT INTO tb_pay_detail (");
                        for (int j = 0; j < addTableModel.getColumnCount(); j++) {
                            sb.append(addTableModel.getColumnName(j));
                            if (j < addTableModel.getColumnCount() - 1) {
                                sb.append(", ");
                            }
                        }
                        sb.append(") VALUES (");
                        for (int j = 0; j < addTableModel.getColumnCount(); j++) {
                            Object value = addTableModel.getValueAt(i, j);
                            // Depending on the column type in your database, you might need to handle different types here
                            if (value instanceof String) {
                                sb.append("'").append(value).append("'");
                            } else {
                                sb.append(value);
                            }
                            if (j < addTableModel.getColumnCount() - 1) {
                                sb.append(", ");
                            }
                        }
                        sb.append(")");

                        // Execute the INSERT statement
                        String insertQuery = sb.toString();
                        Statement insertStmt = conn.createStatement();
                        insertStmt.executeUpdate(insertQuery);
                        insertStmt.close();
                    }
                    JOptionPane.showMessageDialog(addFrame, "数据保存成功！");
                } catch (SQLException ex) {
                    JOptionPane.showMessageDialog(addFrame, "数据保存失败：" + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    ex.printStackTrace();
                }
            }
        });


        JButton returnButton = new JButton("返回");
        returnButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addFrame.dispose();
                try {
                    new PaydetailCURDGUI(e1);// Just close the addFrame without saving
                } catch (SQLException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });

        JPanel buttonPanel = new JPanel();
        buttonPanel.add(addButton);
        buttonPanel.add(saveButton);
        buttonPanel.add(returnButton);

        // Add listener to handle cell updates
        addTable.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int row = addTable.getSelectedRow();
                int column = addTable.getSelectedColumn();
                if (row != -1 && column != -1) {
                    Object value = addTableModel.getValueAt(row, column);
                    // You can perform any update or action with the clicked value here
                }
            }
        });

        addPanel.add(addScrollPane, BorderLayout.CENTER);
        addPanel.add(buttonPanel, BorderLayout.SOUTH);

        addFrame.add(addPanel);
        addFrame.setVisible(true);
    }catch (SQLException ex) {
        ex.printStackTrace();
        JOptionPane.showMessageDialog(null, "数据库查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
    }
}


    // Method to delete selected rows
    private void deleteSelectedRows() {
        // Get the actual table model
        DefaultTableModel model = (DefaultTableModel) table.getModel();

        // Check if table is initialized
        if (table == null) {
            JOptionPane.showMessageDialog(framepaydetail, "Table is not initialized.", "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // Proceed with deleting selected rows
        int[] selectedRows = table.getSelectedRows();
        for (int i = selectedRows.length - 1; i >= 0; i--) {
            int rowIndex = table.convertRowIndexToModel(selectedRows[i]);
            // Ensure rowIndex is within valid range
            if (rowIndex < 0 || rowIndex >= model.getRowCount()) {
                continue; // Skip invalid rows
            }

            // Assuming Eid is stored as a String in the model
            String PDid = (String) model.getValueAt(rowIndex, 0); // Assuming Eid is in the first column

            // Perform delete operation
            String deleteSql = "DELETE FROM tb_pay_detail WHERE PDid = ?";
            try (Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "123456");
                 PreparedStatement pstmt = conn.prepareStatement(deleteSql)) {
                pstmt.setString(1, PDid);
                int rowsAffected = pstmt.executeUpdate();
                if (rowsAffected > 0) {
                    model.removeRow(rowIndex); // Remove row from the table model
                } else {
                    JOptionPane.showMessageDialog(framepaydetail, "Delete operation failed.", "Error", JOptionPane.ERROR_MESSAGE);
                }
            } catch (SQLException ex) {
                ex.printStackTrace();
                JOptionPane.showMessageDialog(framepaydetail, "Database error: " + ex.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // Method to update selected row
    private void updateSelectedRow() {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(framepaydetail, "Please select a row to update.", "Update Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        DefaultTableModel model = (DefaultTableModel) table.getModel();
        StringBuilder sql = new StringBuilder("UPDATE tb_pay_detail SET ");

        java.util.List<String> updateColumns = new ArrayList<>();//存储列名和对应占位符
        List<Object> params = new ArrayList<>();//存储与这些占位符对应的实际参数

        for (int i = 0; i < model.getColumnCount(); i++) {
            String columnName = model.getColumnName(i);//获取列名
            Object value = model.getValueAt(selectedRow, i);//获取模型中特定行 selectedRow 和列 i 的数据值。
            // 跳过主键列 "PDID"
            if (!"PDid".equals(columnName)) {
                // 为更新语句添加列名
                updateColumns.add(columnName + " = ");
                // 存储参数值
                params.add(value);
            }
        }
        int i1=0;
        for(Object updateColumn:updateColumns) {
            for (int i = 0; i < params.size(); i++) {
                Object param = params.get(i1);
                sql.append(updateColumn);
                sql.append("'");
                sql.append(param);
                sql.append("'");
                if(i1 != (updateColumns.size()-1)){
                    sql.append(",");
                }
                i1++;
                break;
            }
        }

        // 添加主键条件
        sql.append(" WHERE PDID = ");
        sql.append("'");
        sql.append(model.getValueAt(selectedRow, 0));
        sql.append("'");
        // 主键值也作为参数传入

        System.out.println(sql.toString());
        // 执行数据库更新操作
        String finalSql = sql.toString();
        try (Connection conn = DriverManager.getConnection(
                "jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "123456");
             PreparedStatement pstmt = conn.prepareStatement(finalSql)) {

            // 执行更新操作
            int rowsUpdated = pstmt.executeUpdate();
            if (rowsUpdated > 0) {
                JOptionPane.showMessageDialog(framepaydetail, "Row updated successfully.", "Update Successful", JOptionPane.INFORMATION_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(framepaydetail, "Failed to update row. No rows affected.", "Update Failed", JOptionPane.ERROR_MESSAGE);
            }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(framepaydetail, "SQL Error: " + e.getMessage(), "Update Failed", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
    }

    public void RedisCopy() throws SQLException {
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC", "root", "123456");Statement stmt = conn.createStatement();
        String query = "SELECT * FROM " + "tb_pay_detail";
        ResultSet rs = stmt.executeQuery(query);
        ResultSetMetaData metaData = rs.getMetaData();
        String listKey = "tb_pay_detail"; // 表名作为列表的键
        while (rs.next()) {
            List<String> rowList = new ArrayList<>();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                rowList.add(rs.getString(i));
            }
            String rowKey = listKey + ":" + rs.getInt("PDid"); // 使用PDid作为列表中元素的键
            Jedis redisClient = new Jedis("localhost", 6379);
            for( String item : rowList)
            {
                redisClient.rpush(rowKey, item);
            }

            redisClient.close();
        }
    }
    public void exportSelectedRowToCsv(JTable table) {
        int selectedRow = table.getSelectedRow();
        if (selectedRow == -1) {
            JOptionPane.showMessageDialog(null, "请选择一个要导出的行。", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        // 调用JFileChooser选择文件路径
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setDialogTitle("选择CSV文件存放路径");
        int result = fileChooser.showSaveDialog(null);
        if (result == JFileChooser.APPROVE_OPTION) {
            File selectedFile = fileChooser.getSelectedFile();
            String csvFilePath = selectedFile.getAbsolutePath();

            // 确保文件名以.csv结尾
            if (!csvFilePath.endsWith(".csv")) {
                csvFilePath += ".csv";
            }

            try (OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(csvFilePath), "UTF-8");
                 PrintWriter pw = new PrintWriter(osw)) {

                TableModel model = table.getModel();
                int columnCount = model.getColumnCount();

                // 写入CSV文件数据
                for (int column = 0; column < columnCount; column++) {
                    Object value = model.getValueAt(selectedRow, column);
                    // 将值转换为字符串，并确保字符串编码为UTF-8
                    String stringValue = (value == null) ? "" : value.toString();
                    pw.print(stringValue);
                    if (column < columnCount - 1) {
                        pw.print(",");
                    }
                }
                pw.println();

                JOptionPane.showMessageDialog(null, "数据导出成功，文件已保存到：" + csvFilePath);
            } catch (IOException e) {
                JOptionPane.showMessageDialog(null, "导出失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                e.printStackTrace();
            }
        } else {
            System.out.println("文件保存操作被取消");
        }
    }
   /* public static void main(String[] args) {
        // Example usage:
        SwingUtilities.invokeLater(() -> {
            try {
                PaydetailCURDGUI p1=new PaydetailCURDGUI();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });
    }*/
}

